package com.mindai.esper.monitor.facade.handler;

import com.mindai.common.exception.BusinessException;
import com.mindai.esper.monitor.biz.enums.BizErrorCode;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ObjectError;

import java.util.List;

/**
 * Created by Ladd on 2016/10/24.
 */

@Slf4j
@Aspect
@Component
public class ParamValidateAspect {

    //配置切入点,该方法无方法体,主要为方便同类中其他方法使用此处配置的切入点
    @Pointcut("execution(* com.mindai.esper.monitor.facade.api..*(..))")
    public void aspect() {
    }

    /*
     * 配置前置通知,使用在方法aspect()上注册的切入点
	 * 同时接受JoinPoint切入点对象,可以没有该参数
	 */
    @Before("aspect()")
    public void before(JoinPoint joinPoint) {
        Object[] params = joinPoint.getArgs();
        for (Object param : params) {
            if (param instanceof Errors) {
                Errors errors = (Errors) param;
                if (errors.hasErrors()) {
                    List<ObjectError> errorList = errors.getAllErrors();
                    StringBuilder sb = new StringBuilder();
                    for (ObjectError error : errorList) {
                        sb.append(error.getDefaultMessage());
                    }
                    log.error("======参数校验异常======" + sb.toString().trim());
                    throw new BusinessException(BizErrorCode.REQUEST_PARAM_ILLEGAL);
                }
            }
        }
    }
}
